package com.bbcare.followup.plat.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.service.IWeChatUserService;

/**
 * @name: 基础儿保演示临时服务
 * @author: hutao
 * @createTime: 2017.5.12
 * @description:
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi/service/wechat")
public class WeChatTempController {
    private final Log logger = LogFactory.getLog(WeChatTempController.class);

    @Autowired
    private IWeChatUserService weChatUserService;

    private static final String notifyUrl ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    private static final String appId ="wx4cfe6f57e9730497";
    private static final String secret ="5123071dff43e89bb8572973afa57085";
    private static final String redis_token ="JCEB_YANSHI_TOKEN";


    /**
     * 提醒
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
	@RequestMapping("/notifyMessage")
	public ResultModel<Map<String, Object>> notifyMessage(@RequestBody String arg) throws Exception {
    	logger.warn("in notifyMessage----arg==" + arg.toString());
    	//openId code 查询
    	Map<String, Object> rspMap = new HashMap<String,Object>();
    	JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String token = weChatUserService.getAccessToken(appId, secret,redis_token);
		String  url = notifyUrl+token ;

		ToolUtils.getWechatInf(url, jsonData.toJSONString());
    	return new ResultModel<Map<String, Object>>(rspMap);
    }


	@RequestMapping("/wechatInitForEbTest")
  	@ResponseBody
  	public void wechatInitForEbTest(HttpServletRequest request, HttpServletResponse response) throws Exception {
  		logger.info("in wechatInitForEbTest----arg==wechatInitForEbTest");
  		Map<String,Object> data = ToolUtils.getParam(request);
  		logger.info("data:["+JSON.toJSONString(data)+"]");
		String timestamp = (String)data.get("timestamp");
		String nonce = (String)data.get("nonce");
		String wxtoken = Constants.TOKEN;
		String signature = (String)data.get("signature");
		String responseStr = "";

		String imageBind ="http://bb-test.oss-cn-shanghai.aliyuncs.com/image/followup/bangdingdangan.png";
		String imageRegister ="http://bb-test.oss-cn-shanghai.aliyuncs.com/image/followup/jiandang.png";
		String imageHospital ="http://bb-test.oss-cn-shanghai.aliyuncs.com/image/followup/yiyuantupian.png";

		String url ="http://doctor.bb-care.com/pss/vipcn/home.html";
		String urlWelcome = url+"?code=21";
		String urlRegister = url+"?code=01";
		String urlBind =url+"?code=02";

		try {
			if (signature.equalsIgnoreCase(ToolUtils.getSignature(timestamp, nonce, wxtoken))) {
				if (org.springframework.util.StringUtils.isEmpty(data.get("echostr"))) {
					String postStr = ToolUtils.readStreamParameter(request.getInputStream());
					logger.info("requestStr:::" + postStr);
					Map<String,Object> wxData = ToolUtils.getXmlElementData(postStr);
					// 获取微信POST过来的数据
					// 用户ID，OPEN_ID
					String fromUserName = (String)wxData.get("FromUserName");
					// 微信原始ID
//					String toUserName = (String)wxData.get("ToUserName");
					// 消息类型
					String msgType = (String)wxData.get("MsgType");
					// 事件类型
					String event = (String)wxData.get("Event");

				    String json ="";
		            String action="";
		        	String title="周家桥街道社区卫生服务中心";
//		        	String hospitalImage="http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/hospital/%E5%A4%A7%E8%BF%9E%E5%B8%82%E5%A6%87%E5%B9%BC%E4%BF%9D%E5%81%A5%E9%99%A2.png";
					String accessToken = weChatUserService.getAccessToken(appId,secret,redis_token);
					if ("event".equals(msgType)){// 事件消息
						if("subscribe".equals(event)){
							 logger.info("in wechatInitForEbTest----关注公众号");
							 String key = (String)wxData.get("EventKey");
							 if(!StringUtils.isEmpty(key)){
				                  action=Constants.MESSAGE_CUSTOM_SEND+accessToken;
			              		  json="{\"touser\":\""+fromUserName+"\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
					              			"{\"title\":\""+title+"\",\"description\":\"\",\"url\":\""+urlWelcome+"\",\"picurl\":\""+imageHospital+"\"}," +
					              			"{\"title\":\"医生未帮您建档请自主建档\",\"description\":\"\",\"url\":\""+urlRegister+"\",\"picurl\":\""+imageRegister+"\"}," +
					              			"{\"title\":\"医生已帮您建档请绑定档案\",\"description\":\"\",\"url\":\""+urlBind+"\",\"picurl\":\""+imageBind+"\"}," +
					              			"]}}";
				             	 ToolUtils.getWechatInf(action,json);
							}else{
			                    //欢迎语
				                action=Constants.MESSAGE_CUSTOM_SEND+accessToken;
				                /*String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				            	String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;*/
				                json="{\"touser\":\""+fromUserName+"\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
				              			"{\"title\":\""+title+"\",\"description\":\"\",\"url\":\""+urlWelcome+"\",\"picurl\":\""+imageHospital+"\"}," +
				              			"{\"title\":\"医生未帮您建档请自主建档\",\"description\":\"\",\"url\":\""+urlRegister+"\",\"picurl\":\""+imageRegister+"\"}," +
				              			"{\"title\":\"医生已帮您建档请绑定档案\",\"description\":\"\",\"url\":\""+urlBind+"\",\"picurl\":\""+imageBind+"\"}," +
				              			"]}}";
				            	ToolUtils.getWechatInf(action,json);
							}
						}else if("SCAN".equals(event)){
							String key = (String)wxData.get("EventKey");
							logger.info("in wechatInitForEbTest----扫码操作,["+key+"]");

		                    action=Constants.MESSAGE_CUSTOM_SEND+accessToken;
		                    json="{\"touser\":\""+fromUserName+"\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
			              			"{\"title\":\""+title+"\",\"description\":\"\",\"url\":\""+urlWelcome+"\",\"picurl\":\""+imageHospital+"\"}," +
			              			"{\"title\":\"医生未帮您建档请自主建档\",\"description\":\"\",\"url\":\""+urlRegister+"\",\"picurl\":\""+imageRegister+"\"}," +
			              			"{\"title\":\"医生已帮您建档请绑定档案\",\"description\":\"\",\"url\":\""+urlBind+"\",\"picurl\":\""+imageBind+"\"}," +
			              			"]}}";
		                 	ToolUtils.getWechatInf(action,json);
						}else if("CLICK".equals(event)){
							String key = (String)wxData.get("EventKey");
							if(("mfpc").equals(key)){
				            	//String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                //String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				             	//String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				             	//String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;

				             	action=Constants.MESSAGE_CUSTOM_SEND+accessToken;
				             	json="{\"touser\":\""+fromUserName+"\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
				              			"{\"title\":\""+title+"\",\"description\":\"\",\"url\":\""+urlWelcome+"\",\"picurl\":\""+imageHospital+"\"}," +
				              			"{\"title\":\"医生未帮您建档请自主建档\",\"description\":\"\",\"url\":\""+urlRegister+"\",\"picurl\":\""+imageRegister+"\"}," +
				              			"{\"title\":\"医生已帮您建档请绑定档案\",\"description\":\"\",\"url\":\""+urlBind+"\",\"picurl\":\""+imageBind+"\"}," +
				              			"]}}";
				              	ToolUtils.getWechatInf(action,json);
			            	}
						}
					}
				} else {
					logger.info("echostr:::" + data.get("echostr"));
					responseStr = (String)data.get("echostr");
					response.getWriter().write(responseStr);
				}
			}else{
				logger.info("token check failed");
				responseStr = "Access Forbidden";
				response.getWriter().write(responseStr);
			}
		}catch (Exception e) {
			logger.error("wechatInitForEbTest Error {}", e);
		}
  	}

}
